package cn.qihua.service.impl;

import java.sql.Timestamp;
import java.util.Collections;
import java.util.List;
import java.util.Set;

import cn.qihua.dao.ISysUserDAO;
import cn.qihua.model.SysUser;
import cn.qihua.security.PasswordHelper;
import cn.qihua.service.IUserService;
import cn.qihua.util.Md5PasswordEncoder;


public class UserService implements IUserService {
	private ISysUserDAO sysUserDAO;
    private PasswordHelper passwordHelper;

	@Override
	public SysUser login(String loginName, String passWord) {
		SysUser u = sysUserDAO.findByUsername(loginName);
		if (u != null
				&& Md5PasswordEncoder.equalsPassword(u.getPassword(),
						passWord.trim())) {
			return u;
		}
		return null;
	}

	@Override
	public Boolean register(SysUser user) {
		if (user == null) {
			return false;
		}
		passwordHelper.encryptPassword(user);
		user.setAddDate(new Timestamp(System.currentTimeMillis()));
		user.setLocked(false);
		//user.setPassword(Md5PasswordEncoder.encodePassword(user.getPassword().trim()));
		return sysUserDAO.save(user);
	}
	
	@Override
	public Boolean changePassword(int userId, String oldPassword,
			String newPassword) {
        SysUser user =sysUserDAO.findById(userId);
        if(passwordHelper.validatePassword(user, oldPassword)){
            user.setPassword(newPassword);
            passwordHelper.encryptPassword(user);
            sysUserDAO.update(user);
            return true;
        }
        return false;
    }
    
	@Override
	public SysUser findById(Integer id) {
		return sysUserDAO.findById(id);
	}

	@Override
	public boolean del(Integer id) {
		SysUser user = sysUserDAO.findById(id);
		if (user != null) {
			sysUserDAO.delete(user);
			return true;
		} else {
			return false;
		}
	}

	@Override
	public Boolean update(SysUser transientInstance) {
		return sysUserDAO.update(transientInstance);
	}

	@Override
	@SuppressWarnings("unchecked")
	public List<SysUser> findAll() {
		return sysUserDAO.findAll();
	}

	@Override
	@SuppressWarnings("unchecked")
	public List<SysUser> findByProperty(String propertyName, Object value) {
		return sysUserDAO.findByProperty(propertyName, value);
	}

	@Override
	@SuppressWarnings("unchecked")
	public List<SysUser> findByLocked(Boolean locked) {
		return sysUserDAO.findByLocked(locked);
	}


	@Override
	public boolean changeLocked(int id, Boolean value) {
		return sysUserDAO.changeLocked(id, value);
	}

	@Override
	public SysUser findByUsername(String username) {
		// TODO Auto-generated method stub
		return sysUserDAO.findByUsername(username);
	}
	
	@Override
	public void setSysUserDAO(ISysUserDAO sysUserDAO) {
		this.sysUserDAO = sysUserDAO;
	}

	public void setPasswordHelper(PasswordHelper passwordHelper) {
		this.passwordHelper = passwordHelper;
	}
}
